var qiniu = require('qiniu-js');
var axios = require('axios');

class gsyQiniu {
  constructor() {
    this.token = ''
    this.domain = ''
    this.config = {
      useCdnDomain: true,
      disableStatisticsReport: false,
      retryCount: 6,
      region: qiniu.region.z1
    };
    this.putExtra = {
      fname: "",
      params: {

      },
      mimeType: null
    };
    this.subscription = ""//控制暂停或者停止的权柄
    // this.getToken()
  }
  initBaseUrl(baseUrl) {
    this.baseUrl = baseUrl;

  }
  async getToken() {
    var result = await axios.get(this.baseUrl + 'qiniu/getToken').then(result => result.data.data)
    this.token = result.uptoken
    this.domain = result.domain

  }
  async upimg({ file, subObject }) {
    await this.getToken()
    let key = this.randomName(18)
    let observable = qiniu.upload(file, key, this.token, this.putExtra, this.config);

    this.subscription = observable.subscribe(subObject);
  }
  async stopUp() {
    this.subscription.unsubscribe()
  }
  randomName(len) {
    len = len || 23;
    var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    var charsLength = chars.length;
    var str = '';
    for (let i = 0; i < len; i++) {
      str += chars.charAt(Math.floor(Math.random() * charsLength))
    }
    return new Date().getTime() + str
  }

}
window.gsyQN = new gsyQiniu()

/** 
 * 
 * 

var config = {
  baseUrl: "http://127.0.0.1:7001/"
}
//例子
let newgsy = new gsyQiniu(config.baseUrl);
let upBtn = document.getElementById('upBtn')
upBtn.onclick = function () {
  var self = this;
  let files = document.getElementById('files')
  var fileEl = files.files[0]
  var data = {
    file: fileEl,
    subObject: {
      next: res => {
        console.log(res)
      },
      error: error => {
        console.log(error)

      },
      complete: res => {
        var url = newgsy.domain + res.key
        console.log(url)
      }
    }
  }
  newgsy.upimg(data)
}
 * 
*/